package com.furongji.education.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.furongji.common.utils.JwtUtil;
import com.furongji.education.config.AuthProperties;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.err.println("gateway全局过滤器.....");
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String excluePath : authProperties.getExcludePathList()) {
            if (antPathMatcher.match(excluePath, path)) {
                return chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        Claims userInfo = JwtUtil.parseToken(token);
        Map<String, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("userId", userInfo.get("userId"));
        userInfoMap.put("usrename", userInfo.get("username"));
        String userInfoJson = new ObjectMapper().writeValueAsString(userInfoMap);

        ServerWebExchange webExchange = exchange.mutate().request(new Consumer<ServerHttpRequest.Builder>() {
            @Override
            public void accept(ServerHttpRequest.Builder builder) {
                builder.header("user-info", userInfoJson);
            }
        }).build();

        return chain.filter(webExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
